<template>
  <div class="airport-ammunition-container">
    <el-row :gutter="20">
      <el-col :span="5">
        <el-card class="query-panel">
          <template #header>
            <div class="card-header">
              <span>查询条件</span>
            </div>
          </template>
          <el-form :model="queryForm" label-width="80px">
            <el-form-item label="地区">
              <el-select v-model="queryForm.region" placeholder="请选择地区">
                <el-option label="全部" value="all" />
                <el-option label="台北地区" value="taipei" />
                <el-option label="台中地区" value="taichung" />
                <el-option label="台南地区" value="tainan" />
                <el-option label="花莲地区" value="hualien" />
                <el-option label="高雄地区" value="kaohsiung" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery" :loading="loading">查询</el-button>
            </el-form-item>
          </el-form>
          
          <!-- 显示错误信息 -->
          <div v-if="error" class="error-message">
            <el-alert
              :title="error"
              type="error"
              show-icon
              :closable="true"
              @close="error = ''"
            />
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="9">
        <el-card class="map-container">
          <template #header>
            <div class="card-header">
              <span>机场分布图</span>
              <div class="info-text">气泡大小代表弹药库总面积</div>
            </div>
          </template>
          <div id="airportChart" class="chart" ref="airportChartRef"></div>
          <div v-if="loading" class="loading-overlay">
            <div class="spinner"></div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="10">
        <el-card class="depots-container">
          <template #header>
            <div class="card-header">
              <span>机场关联弹药库</span>
              <div v-if="selectedAirport" class="selected-info">
                {{ selectedAirport.name }} ({{ getRegionName(selectedAirport.region) }})
              </div>
            </div>
          </template>
          <div v-if="!selectedAirport" class="no-selection">
            <el-empty description="请在左侧地图选择一个机场" />
          </div>
          <div v-else class="depot-list">
            <div class="airport-info">
              <div class="info-row">
                <span class="label">机场名称:</span>
                <span class="value">{{ selectedAirport.name }}</span>
              </div>
              <div class="info-row">
                <span class="label">所在区域:</span>
                <span class="value">{{ getRegionName(selectedAirport.region) }}</span>
              </div>
              <div class="info-row">
                <span class="label">弹药库数量:</span>
                <span class="value">{{ selectedAirport.depot_count }} 座</span>
              </div>
              <div class="info-row">
                <span class="label">总面积:</span>
                <span class="value">{{ selectedAirport.total_area.toFixed(2) }} 平方米</span>
              </div>
            </div>
            
            <div class="divider"></div>
            
            <h3>关联弹药库列表 ({{ selectedDepots.length }})</h3>
            <el-table :data="selectedDepots" stripe style="width: 100%">
              <el-table-column prop="name" label="名称" min-width="120" />
              <el-table-column prop="type" label="类型" width="120">
                <template #default="scope">
                  <el-tag :type="getTypeTag(scope.row.type)">
                    {{ getFacilityTypeName(scope.row.type) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="area" label="面积(㎡)" width="100" />
              <el-table-column prop="location" label="详细位置" min-width="150" />
            </el-table>
          </div>
          <div v-if="loading" class="loading-overlay">
            <div class="spinner"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import { ElMessage } from 'element-plus'
import { getAirportsWithDepots } from '@/api/ammunition-supply'

// 查询表单
const queryForm = ref({
  region: 'all'
})

// 加载状态
const loading = ref(false)
// 错误状态
const error = ref('')

// 数据
const airportsData = ref([])
const selectedAirport = ref(null)
const selectedDepots = ref([])

// 图表DOM引用
const airportChartRef = ref(null)
// 图表实例
let airportChart = null

// 地区名称映射
const regionNames = {
  all: '全部',
  taipei: '台北地区',
  taichung: '台中地区',
  tainan: '台南地区',
  hualien: '花莲地区',
  kaohsiung: '高雄地区'
}

// 获取区域名称
const getRegionName = (region) => {
  return regionNames[region] || region
}

// 获取设施类型名称
const getFacilityTypeName = (facilityType) => {
  const typeNames = {
    'production': '弹药制造厂',
    'central': '中央弹药库',
    'airport_depot': '机场弹药库',
    'standard': '标准弹药库',
    'special': '特种弹药库',
    'airport': '军用机场'
  }
  return typeNames[facilityType] || facilityType
}

// 获取设施类型对应的标签类型
const getTypeTag = (facilityType) => {
  const tagTypes = {
    'production': 'primary', 
    'central': 'danger',
    'airport_depot': 'success',
    'standard': 'success',
    'special': 'warning',
    'airport': 'info'
  }
  return tagTypes[facilityType] || 'info'
}

// 窗口调整处理
const handleWindowResize = () => {
  try {
    if (airportChart) {
      airportChart.resize()
    }
  } catch (err) {
    console.error('窗口大小调整时出错:', err)
  }
}

// 查询数据
const handleQuery = async () => {
  await loadAirportsData()
}

// 加载机场及关联弹药库数据
const loadAirportsData = async () => {
  loading.value = true
  error.value = ''
  
  try {
    console.log('加载机场及弹药库数据, 参数:', { region: queryForm.value.region })
    const response = await getAirportsWithDepots({ region: queryForm.value.region })
    console.log('机场数据响应:', response)
    
    // 处理响应数据
    const data = response.data || response
    
    // 验证数据
    if (!Array.isArray(data)) {
      throw new Error('无效的数据格式')
    }
    
    // 更新数据
    airportsData.value = data
    
    // 如果没有数据，显示提示
    if (data.length === 0) {
      ElMessage.warning('未找到任何机场数据')
      // 清空选中状态
      selectedAirport.value = null
      selectedDepots.value = []
    } else {
      // 更新图表
      await nextTick()
      // 确保图表实例初始化
      if (!airportChart) {
        initAirportChart()
      }
      
      // 更新散点图
      updateAirportChart()
      
      ElMessage({
        message: `成功加载了 ${data.length} 个机场数据`,
        type: 'success'
      })
    }
  } catch (err) {
    console.error('加载机场数据失败:', err)
    error.value = `加载机场数据失败: ${err.message || '未知错误'}`
    ElMessage.error('无法加载机场数据')
  } finally {
    loading.value = false
  }
}

// 初始化机场散点图
const initAirportChart = () => {
  try {
    // 确保DOM容器已挂载
    if (!airportChartRef.value) {
      console.error('机场图表容器未挂载')
      return
    }
    
    console.log('初始化机场散点图...')
    
    // 初始化图表实例
    airportChart = echarts.init(document.getElementById('airportChart'))
    
    // 配置基本选项
    const option = {
      title: {
        text: '机场分布及弹药库规模',
        left: 'center',
        top: 10
      },
      tooltip: {
        trigger: 'item',
        formatter: function(params) {
          const airport = params.data.airport
          return `
            <div style="font-weight:bold">${airport.name}</div>
            <div>区域: ${getRegionName(airport.region)}</div>
            <div>弹药库数量: ${airport.depot_count} 座</div>
            <div>总面积: ${airport.total_area.toFixed(2)} 平方米</div>
            <div>点击查看详情</div>
          `
        }
      },
      visualMap: {
        type: 'continuous',
        min: 0,
        max: 10000,
        text: ['大', '小'],
        inRange: {
          symbolSize: [10, 70],
          color: ['#51689b', '#ce5c5c']
        },
        textStyle: {
          color: '#333'
        },
        right: 0,
        bottom: 30
      },
      geo: {
        map: 'taiwan',
        roam: true,
        zoom: 1.2,
        label: {
          emphasis: {
            show: false
          }
        },
        itemStyle: {
          normal: {
            areaColor: '#e0e0e0',
            borderColor: '#ccc'
          },
          emphasis: {
            areaColor: '#d5d5d5'
          }
        }
      },
      series: [{
        name: '机场弹药分布',
        type: 'scatter',
        coordinateSystem: 'geo',
        data: [],
        symbolSize: function (val) {
          return 20 + Math.sqrt(val[2]) / 5
        },
        itemStyle: {
          color: '#51689b',
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.3)'
        },
        emphasis: {
          label: {
            show: true,
            formatter: '{b}',
            position: 'top'
          }
        }
      }]
    }
    
    // 注册中国台湾地图
    airportChart.showLoading()
    
    // 获取台湾地图JSON
    fetch('/assets/map-of-taiwan/taiwan.json')
      .then(response => response.json())
      .then(taiwanJson => {
        airportChart.hideLoading()
        echarts.registerMap('taiwan', taiwanJson)
        airportChart.setOption(option)
        
        // 添加点击事件
        airportChart.on('click', (params) => {
          if (params.seriesType === 'scatter') {
            selectAirport(params.data.airport)
          }
        })
        
        // 初始绘制
        updateAirportChart()
        
        console.log('机场散点图初始化完成')
      })
      .catch(err => {
        airportChart.hideLoading()
        console.error('加载台湾地图数据失败:', err)
        error.value = '无法加载地图数据'
      })
  } catch (err) {
    console.error('初始化机场散点图失败:', err)
    error.value = `初始化机场散点图失败: ${err.message || '未知错误'}`
  }
}

// 更新机场散点图
const updateAirportChart = () => {
  try {
    if (!airportChart) {
      console.error('机场散点图实例不存在')
      return
    }
    
    if (!airportsData.value || !airportsData.value.length) {
      console.warn('没有机场数据可以显示')
      return
    }
    
    console.log('正在更新机场散点图...')
    
    // 准备散点图数据
    const scatterData = airportsData.value.map(item => {
      return {
        name: item.airport.name,
        value: [
          item.airport.longitude,
          item.airport.latitude,
          item.airport.total_area || 0
        ],
        airport: item.airport,
        depots: item.depots
      }
    })
    
    // 更新图表数据
    airportChart.setOption({
      visualMap: {
        max: Math.max(...scatterData.map(item => item.value[2])) || 10000
      },
      series: [{
        data: scatterData
      }]
    })
    
    console.log('机场散点图更新完成')
  } catch (err) {
    console.error('更新机场散点图失败:', err)
    error.value = `更新机场散点图失败: ${err.message || '未知错误'}`
  }
}

// 选择机场并显示其关联的弹药库
const selectAirport = (airport) => {
  try {
    console.log('选择机场:', airport)
    
    // 设置选中的机场
    selectedAirport.value = airport
    
    // 获取选中机场的弹药库列表
    const airportData = airportsData.value.find(item => item.airport.id === airport.id)
    
    if (airportData && airportData.depots) {
      selectedDepots.value = airportData.depots
      console.log('关联弹药库:', selectedDepots.value)
    } else {
      selectedDepots.value = []
      console.warn('未找到关联弹药库')
    }
  } catch (err) {
    console.error('选择机场时出错:', err)
    error.value = `选择机场时出错: ${err.message || '未知错误'}`
  }
}

// 生命周期钩子
onMounted(async () => {
  try {
    console.log('机场弹药分布视图已挂载，开始初始化...')
    
    // 监听窗口调整事件
    window.addEventListener('resize', handleWindowResize)
    
    // 先初始化图表
    await nextTick()
    initAirportChart()
    
    // 加载数据
    await loadAirportsData()
    
    console.log('机场弹药分布视图初始化完成')
  } catch (err) {
    console.error('视图初始化失败:', err)
    error.value = `初始化失败: ${err.message || '未知错误'}`
  }
})

// 组件卸载时清理
onUnmounted(() => {
  // 移除窗口调整事件
  window.removeEventListener('resize', handleWindowResize)
  
  // 销毁图表实例
  if (airportChart) {
    airportChart.dispose()
    airportChart = null
  }
})
</script>

<style scoped>
.airport-ammunition-container {
  padding: 20px;
  height: 100vh;
  overflow: hidden;
}

.query-panel, .map-container, .depots-container {
  height: calc(100vh - 40px);
  overflow-y: auto;
}

.chart {
  width: 100%;
  height: 100%;
  min-height: 500px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-text {
  font-size: 13px;
  color: #909399;
}

.selected-info {
  font-size: 14px;
  color: #409EFF;
  font-weight: 500;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.spinner {
  width: 40px;
  height: 40px;
  border: 4px solid rgba(0, 123, 255, 0.2);
  border-radius: 50%;
  border-top-color: #007bff;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.no-selection {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  min-height: 300px;
}

.airport-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
}

.label {
  width: 90px;
  color: #606266;
}

.value {
  flex: 1;
  font-weight: 500;
  color: #303133;
}

.divider {
  height: 1px;
  background-color: #ebeef5;
  margin: 20px 0;
}

h3 {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 15px;
}
</style> 